package 极客算法训练营.chapter10;

import javafx.util.Pair;

import java.util.HashSet;
import java.util.Set;

public class 模拟行走机器人 {
    class Solution {
        public int robotSim(int[] commands, int[][] obstacles) {
            //使用Set存储障碍点
            Set<Pair<Integer, Integer>> obsPoints = new HashSet<>();
            for (int[] obstacle : obstacles) {
                obsPoints.add(new Pair<>(obstacle[0], obstacle[1]));
            }
            int[] dx = {0, 1, 0, -1};
            int[] dy = {1, 0, -1, 0};
            int direction = 0;//方向标识,0表示向前，1表示向右，3表示向左
            int x = 0;
            int y = 0;
            int maxDistance = 0;
            for (int i = 0; i < commands.length; i++) {
                if (commands[i] == -2) {
                    direction = (direction + 3) % 4;
                } else if (commands[i] == -1) {
                    direction = (direction + 1) % 4;
                } else {//在当前方向直走
                    for (int j = 0; j < commands[i]; j++) {
                        int newX = x + dx[direction];
                        int newY = y + dy[direction];
                        if (obsPoints.contains(new Pair<>(newX, newY))) {
                            break;
                        }
                        x = newX;
                        y = newY;
                        maxDistance = Math.max(maxDistance, x * x + y * y);
                    }
                }
            }
            return maxDistance;
        }
    }
}
